package com.wing.cabinet.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.cabinet.model.entity.UseInventoryUser;
import com.wing.cabinet.model.request.UseInventoryUserForm;
import com.wing.cabinet.model.response.UseInventoryProductVO;
import com.wing.cabinet.model.response.UseInventoryUserVO;
import com.wing.cabinet.service.UseInventoryInoutDetailService;
import com.wing.cabinet.service.UseInventoryUserService;
import com.wing.cabinet.utils.ExcelUtils;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.entity.Product;
import com.wing.product.model.response.ProductDetailVO;
import com.wing.product.service.ProductDetailService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.UseInventoryUserExcelIn;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-用户产品在用库存管理", tags = "#/cabinet/useInventoryUser")
@RestController("useInventoryUserController")
@RequestMapping("cabinet/admin/useInventoryUser")
@RequiredArgsConstructor
@Slf4j
public class UseInventoryUserController {

    private final UseInventoryUserService useInventoryUserService;

    private final UseInventoryInoutDetailService useInventoryInoutDetailService;

    private final ProductDetailService productDetailService;

    @ApiOperation(value = "查询所有用户产品在用库存", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<UseInventoryUserVO> list(
            @RequestParam(name = "page",defaultValue = "1") Integer page
            ,@RequestParam(name = "limit",defaultValue = "10") Integer limit
            ,@RequestParam(name = "sort",defaultValue = "id") String sort
            ,@RequestParam(name = "order",defaultValue = "desc") String order
            ,String deviceCode
            ,Long productCategoryId
            ,Long productTypeId
            ,String cabCodes
            ,String skuName
            ,String brandName
            ,String typeName
            ,String name
            ,String orderCode
            ,String oldSpecCode
            ,String skuCode
            ,String query
            ,String startTime
            ,String endTime
            ,Long creatorId
            ,String creatorName
            ,String mainCabCode
    ) {
        Page<UseInventoryProductVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        params.put("queryFlag","useInventoryProduct4App");
        params.put("deviceCode",deviceCode);
        params.put("productCategoryId",productCategoryId);
        params.put("productTypeId",productTypeId);
        if (StringUtils.isNotBlank(cabCodes)){
            String [] cabCodeArray=cabCodes.split(",");
            params.put("cabCodes",cabCodeArray);
        }
        params.put("skuName",skuName);
        params.put("skuCode",skuCode);
        params.put("brandName",brandName);
        params.put("typeName",typeName);
        params.put("name",name);
        params.put("creatorName",creatorName);

        params.put("deviceCode",deviceCode);
        params.put("orderCode",orderCode);
        params.put("queryFlag","query4web");
        params.put("oldSpecCode",oldSpecCode);

        params.put("startCreateTime",startTime);
        params.put("endCreateTime",endTime);
        if (creatorId!=null){
            params.put("creatorId",creatorId);
        }
        params.put("enterpriseCode", JwtUtils.getEnterpriseCode());
        if (StringUtils.isNotBlank(query)){
            params.put("query",query);
        }
        if (StringUtils.isNotBlank(mainCabCode)){
            params.put("belongCabinet", mainCabCode);
        }
        Page<UseInventoryUserVO> list = useInventoryUserService.pageList4app(pg, params);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }




    @ApiOperation(value = "添加用户产品在用库存", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(UseInventoryUserForm.Add.class) UseInventoryUserForm useInventoryUserForm) {
        if (useInventoryUserService.add(useInventoryUserForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }




    @ApiOperation(value = "修改用户产品在用库存", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(UseInventoryUserForm.Update.class) UseInventoryUserForm useInventoryUserForm) {
        UseInventoryUser useInventoryUser = useInventoryUserService.getById(useInventoryUserForm.getId());
        if(useInventoryUser == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(UseInventoryUser.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(useInventoryUserForm, useInventoryUser, copyOptions);
        if (useInventoryUserService.updateById(useInventoryUser)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



@ApiOperation(value = "删除用户产品在用库存", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "useInventoryUserId", value = "用户产品在用库存id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long useInventoryUserId) {
        if (useInventoryUserService.removeById(useInventoryUserId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    /**
     * 下载产品数据录入excel模板
     */
    @ApiOperation(value = "下载产品数据录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"创建人","物料编码","设备编号","数量"};
        String[] indexArr = {"2","3","6","7","8"};
        List<String[]> downData = new ArrayList<>();
        DownExcelUtil.createExcelTemplate(response, request, "在用刀具导入模板", Arrays.asList(headerArr),downData, Arrays.asList(indexArr));
    }

    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("上传文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<UseInventoryUserExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<UseInventoryUserExcelIn> list = reader.read(is,UseInventoryUserExcelIn.class);
            //List<Product> productList = new ArrayList<>();
            Map<String, Product> productMap = new HashMap<String, Product>();
            int i = 1;
            for (UseInventoryUserExcelIn useInventoryUserExcelIn : list) {
                i++;
                // 查询skuCode是否已经存在
                ProductDetailVO detailVO = productDetailService.getProductDetailBySkuCode(useInventoryUserExcelIn.getSkuCode());
                if(null == detailVO){
                    return JsonResult.fail("第"+i+"行物料编码不存在");
                }
            }
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            useInventoryInoutDetailService.importExcel(list);
        } catch (Exception e) {
        //e.printStackTrace();
        log.error("上传文件异常！异常信息:", e);
        return JsonResult.exception("上传文件异常！异常信息:" + e.getMessage());
    }
        return JsonResult.success("上传成功！");
    }

    @ApiOperation(value = "导出在用统计数据")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        List<UseInventoryUserVO> list = new ArrayList<>();
        Map paramsMap = new HashMap();
        //paramsMap.put("productName",productName);

        list = useInventoryUserService.ecxportList(paramsMap);

        ExcelUtils.export(response,"未归还记录",list,UseInventoryUserVO.class);
    }


}
